# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.forms import ModelForm
from app_accounts.models import *
from app_accounts.forms import *
from django.contrib.auth import authenticate
import django.utils.timezone as timezone
from django.views.decorators.csrf import csrf_exempt
from django import forms
from django.core.exceptions import ValidationError
import re
import json
import datetime
import os

class LoginForm(forms.Form):
    user = forms.CharField(required=True,
                        max_length=15,
                        widget=forms.TextInput(attrs={'placeholder':'用户名'}),
                        error_messages={'required': '用户名不能为空.','max_length':"最多15位"})
    pwd = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.TextInput(attrs={'placeholder':'密码','type':'password'}),
                        error_messages={'required': '密码不能为空.', 'max_length':"最多20位"})
    def clean(self):
        cleaned_data = self.cleaned_data
        user = cleaned_data.get('user')
        PassWord = cleaned_data.get('pwd')
        userID=TuringUser.objects.filter(UserID=user)
        if not userID:
            raise forms.ValidationError('用户不存在!')
        else:
            Valid=authenticate(username=user,password=PassWord)
            if Valid is None:
                raise forms.ValidationError('密码错误!')
        return cleaned_data


def mobile_validate(value):
    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
    if not mobile_re.match(value):
        raise ValidationError('手机号码格式错误')

def qq_validate(value):
    qq_re=re.compile(r'^[1-9][0-9]{5,11}$')
    if not qq_re.match(value):
        raise ValidationError('qq格式错误')

class RegisterForm(forms.Form):
    user = forms.CharField(required=True,
                        min_length=6,
                        max_length=15,
                        error_messages={'required': '用户名不能为空','min_length': "用户名至少6位",'max_length':"用户名最多15位"})
    pwd = forms.CharField(required=True,
                        max_length=20,
                        widget=forms.PasswordInput,
                        error_messages={'required':'密码不能为空','max_length':"密码最多20位"})
    pwd2 = forms.CharField(required=False,
                        max_length=20,
                        widget=forms.PasswordInput,)
    nickname = forms.CharField(required=True,
                            max_length=20,
                            error_messages={'required': '昵称不能为空','max_length':'昵称最多20位'})
    email = forms.EmailField(error_messages={'required': '电子邮箱不能为空', 'invalid':'邮箱格式不正确'})
    qq = forms.CharField(required=False,validators=[qq_validate, ])
    phone = forms.CharField(validators=[mobile_validate, ], required=False)

    def clean_user(self):
        user = self.cleaned_data.get('user')
        userID=TuringUser.objects.filter(UserID=user)
        if userID:
            raise forms.ValidationError('用户名已经注册!')
        return user

    def clean_email(self):
        email = self.cleaned_data.get('email')
        user = TuringUser.objects.filter(UserEmail=email)
        if user:
            raise forms.ValidationError('邮箱已注册!')
        return email

    def clean(self):
        cleaned_data = self.cleaned_data
        if cleaned_data.has_key('pwd') and cleaned_data.has_key('pwd2'):
            pwd = cleaned_data['pwd']
            pwd2 = cleaned_data['pwd2']
            if pwd != pwd2:
                raise forms.ValidationError('二次输入密码不匹配')
        return cleaned_data

@csrf_exempt
def UserCheck(request):
    if request.POST:
        username=request.POST.get('username')
        user=TuringUser.objects.filter(UserID=username)
        if user:
            dic={'info':1}
            data=json.dumps(dic)
            return HttpResponse(data)
        else:
            dic={'info':0}
            data=json.dumps(dic)
            return HttpResponse(data)

@csrf_exempt
def EmailCheck(request):
    if request.POST:
        email=request.POST.get('email')
        user=TuringUser.objects.filter(UserEmail=email)
        if user:
            dic={'info':1}
            data=json.dumps(dic)
            return HttpResponse(data)
        else:
            dic={'info':0}
            data=json.dumps(dic)
            return HttpResponse(data)

@csrf_exempt
def register(request):
    if request.POST:
        objPost = RegisterForm(request.POST)
        ret = objPost.is_valid()
        if ret:
            UserID=objPost.cleaned_data['user']
            PassWord=objPost.cleaned_data['pwd']
            NewUser = User.objects.create_user(username = UserID, password = PassWord)
            string=''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(16)))
            TuringUser(Note=string,CurrentTime=timezone.now(),LastLoginTime=timezone.now(),RoleTypeID="student",UserQQ=objPost.cleaned_data['qq'],MobilePhone=objPost.cleaned_data['phone'],Users=NewUser,UserID=UserID,NickName=objPost.cleaned_data['nickname'],UserEmail=objPost.cleaned_data['email']).save()
            #send_mail('TuringClass','Click the URL below to finish your registration, the URL will be disabled in two days!\n http://127.0.0.1:8000/ValidateEmail/?UserID='+UserID+'&key='+string,'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
            request.session['UserID']=UserID
            return HttpResponseRedirect('/PersonalInfo/')
        else:
            pass
        return render(request, 'register.html', {'obj1': objPost})
    else:
        if not request.session.has_key('UserID'):
            objGet = RegisterForm()
            return render(request, 'register.html', {'obj1': objGet})
        else:
            return HttpResponseRedirect('/PersonalInfo/')

def ValidateEmail(request):
    if request.GET:
        key=request.GET.get('key')
        UserID=request.GET.get('UserID')
        try:
            user=TuringUser.objects.get(UserID=UserID)
        except:
            return HttpResponse('Whoops!')
        if user.Enabled==True:
            return HttpResponseRedirect('/Accounts/login/')
        if key!=user.Note:
            return HttpResponse('Whoops!')
        user.Enabled=True;
        request.session['UserID']=UserID
        user.Note="None"
        user.LastLoginTime=user.CurrentTime
        user.CurrentTime=timezone.now()
        user.save()
        return HttpResponseRedirect('/PersonalInfo/')

@csrf_exempt
def login(request):
    context = {}
    context['Login_active'] = True
    if request.POST:
        objPost = LoginForm(request.POST)
        ret = objPost.is_valid()
        if ret:
            UserID=objPost.cleaned_data['user']
            request.session['UserID']=UserID
            user=TuringUser.objects.get(UserID=UserID)
            user.LastLoginTime=user.CurrentTime
            user.CurrentTime=timezone.now()
            user.save()
            return HttpResponseRedirect('/PersonalInfo/')
        else:
            pass

        context['obj1'] = objPost
        return render(request,'accountlogin.html', context)
    else:
        if not request.session.has_key('UserID'):
            objGet = LoginForm()
            context['obj1'] = objGet
            return render(request,'accountlogin.html', context)
        else:
            return HttpResponseRedirect('/PersonalInfo/')

@csrf_exempt
def logout(request):
    if request.session.has_key('UserID'):
        request.session.pop('UserID')
    return HttpResponseRedirect('/Accounts/login/')
